package com.prism.e4.rcp.ui.handlers;

import java.io.File;

import javax.inject.Named;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.prism.e4.rcp.ui.parts.E4PrismEditor;

public class SaveModelAsHandler {
	
	@Execute
	public void execute(
			@Named(IServiceConstants.ACTIVE_SHELL) Shell parentShell,
			MApplication application, EModelService modelService,
			final EPartService partService, final IWorkspace workspace,
			final IProgressMonitor monitor) {

		MPart existedPart = (MPart) modelService.find(
				"com.prism.e4.rcp.inputpart", application);
		if (!existedPart.isVisible())
			existedPart.setVisible(true);
		E4PrismEditor editor = (E4PrismEditor) existedPart.getObject();

		FileDialog fDialog = new FileDialog(parentShell, SWT.SAVE);
		fDialog.setFilterNames(new String[] { "All Files (*.*)" });
		fDialog.setFilterExtensions(new String[] { "*.*" });
		String fileName = fDialog.open();
		if (fileName == null)
			return;
		if (new File(fileName).exists()) {
			MessageBox mb = new MessageBox(fDialog.getParent(),
					SWT.ICON_WARNING | SWT.YES | SWT.NO);
			mb.setMessage(fileName
					+ " already exists, do you want to replace it?");
			if (mb.open() == SWT.NO)
				return;
		}
		existedPart
				.setLabel(fileName.substring(fileName.lastIndexOf("\\") + 1));
		//TODO: save file
		editor.dirty.setDirty(false);
	}
}
